<template>
  <div class="div-triplet d-flex w-100">
    <!-- 左侧行数栏 -->
    <div class="div-line-numbers d-flex flex-column">
      <label
        class="lbl-line-number"
        :class="{ 'lbl-line-number-error': errorLineNumbersRef.includes(i) }"
        v-for="i in lineCount"
        :key="i"
      >
        {{ i }}
      </label>
    </div>
    <!-- 文本栏 -->
    <textarea
      class="ta-triplet-text flex-grow-1"
      wrap="off"
      v-model="tripletText"
    />
  </div>
</template>

<script>
import { ref, watch, computed } from "vue";

export default {
  props: {
    modelValue: {
      type: String,
      required: true,
    },
    errorLineNumbers: {
      type: Array,
      required: true,
    },
  },
  setup(props, { emit }) {
    const tripletText = ref(props.modelValue);
    const errorLineNumbersRef = ref(props.errorLineNumbers);

    const lineCount = computed(() => {
      let lineCountNew = 1;

      for (const i of tripletText.value) {
        if (i === "\n") {
          lineCountNew++;
        }
      }

      return lineCountNew;
    });

    watch(
      () => props.modelValue,
      (newValue) => (tripletText.value = newValue)
    );
    watch(
      () => props.errorLineNumbers,
      (newValue) => (errorLineNumbersRef.value = newValue),
      { deep: true }
    );

    watch(tripletText, (newValue) => {
      errorLineNumbersRef.value = [];
      emit("update:modelValue", newValue);
    });
    watch(
      errorLineNumbersRef,
      (newValue) => emit("update:errorLineNumbers", newValue),
      { deep: true }
    );

    return {
      tripletText,
      lineCount,
      errorLineNumbersRef,
    };
  },
};
</script>

<style lang="scss" scoped>
.div-triplet {
  font-size: 15px;
  overflow: auto;
}

.div-line-numbers {
  padding: 2px 0;
  border: 1px solid #ced4da;
  border-right: 0;
  border-top-left-radius: 0.25rem;
  border-bottom-left-radius: 0.25rem;
  user-select: none;
}

.lbl-line-number {
  padding: 0 5px;
}

.lbl-line-number-error {
  background-color: rgb(162, 0, 0);
  color: white;
}

.ta-triplet-text {
  padding: 2px;
  border: 1px solid #ced4da;
  border-top-right-radius: 0.25rem;
  border-bottom-right-radius: 0.25rem;
  resize: none; // 隐藏右下角改变大小框
  outline: none;
}
</style>